/**
 * @param {import('jquery')} $
 */
(function ($) {
    /**
     * 
     * @param {JQuery<HTMLSelectElement>} select
     * @param {any} opt 
     */
    function Select (select, opt) {
        select = $(select)
        if (select.data('simple-select-init')) {
            return;
        }
        select.data('simple-select-init', true)
        
        var holder = $('<div class="simple-select"/>');
        var show = $('<span>' + select.children().eq(0).text() + '</span>')
        var list = $('<div class="simple-select-list"></div>')

        select.children().each(function () {
            var option = $(this)
            var value = option.attr('value')
            if (option.prop('selected')) {
                show.text(option.text())
                if (!value) {
                    show.addClass('simple-select-default')
                }
            }
            var item = $('<a href="javascript:;" data-value="'+value+'">'+ option.text() +'</a>')
            list.append(item)
        })

        holder.css({ width: opt.width })
        holder.on('click', function (e) {
            var t = $(this)
            var offset = t.offset()
            var width = t.width()
            var height = t.height()
            list.css({
                width: width,
                left: offset.left,
                top: offset.top + height
            });
            if ($(e.target).parents().has(holder).length) {
                setTimeout(() => {
                    list.show()
                }, 0);
            }
        }).append(show)

        $(document).on('click', function (e) {
            if ($(e.target).parents().has(holder).length) {
                list.hide()
            }
        })

        list.on('click', 'a', function () {
            var value = $(this).data('value')
            show.text($(this).text())
            if (!value) {
                show.addClass('simple-select-default')
            } else {
                show.removeClass('simple-select-default')
            }
            select.val(value).trigger('change')
        })

        select.after(holder).hide()
        $(document.body).append(list)
    }

    $.fn.MySelect = function (opt) {
        return this.each(function (ele) {
            var t = $(ele)
            var width = 100
            try {
                width = t.width()
            } catch (e) {}
            Select(this, $.extend({
                width: t.data('width') || width,
            }, opt))
        })
    }

})(jQuery)